import { defineStore } from 'pinia'
import { 
  getAllTags, 
  getTagById, 
  createTag, 
  updateTag, 
  deleteTag 
} from '@/api/tags'

export const useTagStore = defineStore('tags', {
  state: () => ({
    tags: [], // 确保初始化为空数组
    currentTag: null,
    isLoading: false,
    error: null
  }),

  actions: {
    async fetchAllTags() {
      this.isLoading = true
      this.error = null
      try {
        const response = await getAllTags()
        // 确保正确处理响应数据
        this.tags = response.data || []
        return this.tags
      } catch (error) {
        this.error = error.response?.data?.message || '获取标签失败'
        this.tags = [] // 确保设置为空数组
        return []
      } finally {
        this.isLoading = false
      }
    },

    async fetchTagById(id) {
      this.isLoading = true
      this.error = null
      try {
        const response = await getTagById(id)
        this.currentTag = response.data
        return this.currentTag
      } catch (error) {
        this.error = error.response?.data?.message || '获取标签详情失败'
        this.currentTag = null
        return null
      } finally {
        this.isLoading = false
      }
    },

    async createNewTag(tagData) {
      this.isLoading = true
      this.error = null
      try {
        const response = await createTag(tagData)
        this.tags.push(response.data)
        return response.data
      } catch (error) {
        this.error = error.response?.data?.message || '创建标签失败'
        return null
      } finally {
        this.isLoading = false
      }
    },

    async updateExistingTag(id, tagData) {
      this.isLoading = true
      this.error = null
      try {
        const response = await updateTag(id, tagData)
        const index = this.tags.findIndex(t => t.id === id)
        if (index !== -1) {
          this.tags.splice(index, 1, response.data)
        }
        if (this.currentTag && this.currentTag.id === id) {
          this.currentTag = response.data
        }
        return response.data
      } catch (error) {
        this.error = error.response?.data?.message || '更新标签失败'
        return null
      } finally {
        this.isLoading = false
      }
    },

    async deleteExistingTag(id) {
      this.isLoading = true
      this.error = null
      try {
        await deleteTag(id)
        this.tags = this.tags.filter(t => t.id !== id)
        if (this.currentTag && this.currentTag.id === id) {
          this.currentTag = null
        }
        return true
      } catch (error) {
        this.error = error.response?.data?.message || '删除标签失败'
        return false
      } finally {
        this.isLoading = false
      }
    }
  }
})